<template>
<div class="min-h-screen bg-gray-50">


	<!-- 主要内容区域 -->
	<div class="container mx-auto px-8 py-8 pt-28">
		<!-- 页面标题和操作按钮 -->
		<div class="flex justify-between items-start mb-8">
			<div>
				<h1 class="text-3xl font-bold text-gray-900 mb-2">我的班级</h1>
				<p class="text-gray-600">查看管理的班级和处理学生申请</p>
			</div>
			<div class="flex gap-4">
				<el-button type="primary" size="large" class="flex items-center gap-2"
					@click="showJoinDialog = true">
					<el-icon>
						<Plus />
					</el-icon>
					创建班级
				</el-button>
				<el-button type="danger" size="large"
					@click="logout">
					退出登录
				</el-button>
			</div>
		</div>

		<!-- 统计卡片 -->
		<div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
			<div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
				<div class="flex items-center justify-between">
					<div>
						<p class="text-sm text-gray-500 mb-1">管理班级数</p>
						<h3 class="text-3xl font-bold text-gray-900">{{ stats.joinedClasses }}</h3>
					</div>
					<div class="p-3 bg-blue-100 rounded-full">
						<el-icon class="text-blue-600">
							<School />
						</el-icon>
					</div>
				</div>
			</div>

			<div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 cursor-pointer hover:shadow-md transition-shadow"
				@click="showProcessedDialog = true">
				<div class="flex items-center justify-between">
					<div>
						<p class="text-sm text-gray-500 mb-1">处理申请</p>
						<h3 class="text-3xl font-bold text-gray-900">{{ stats.totalCourses }}</h3>
					</div>
					<div class="p-3 bg-green-100 rounded-full">
						<el-icon class="text-green-600">
							<Check />
						</el-icon>
					</div>
				</div>
			</div>
		</div>

		<!-- 我的班级列表 -->
		<div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
			<div class="px-6 py-4 border-b border-gray-200">
				<h2 class="text-lg font-medium text-gray-900">我的班级</h2>
			</div>

			<div v-if="loading" class="flex flex-col items-center justify-center h-40">
			<div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
			<span class="mt-2 text-gray-500">加载中...</span>
		</div>

			<div v-else-if="myClasses.length === 0" class="p-8 text-center">
				<el-empty description="暂无班级" />
			</div>

			<div v-else class="divide-y divide-gray-200">
				<div v-for="classItem in myClasses" :key="classItem.id"
					class="px-6 py-4 hover:bg-gray-50 transition-colors cursor-pointer"
					@click="viewClassDetail(classItem)">
					<div class="flex items-center justify-between">
						<div class="flex items-center gap-4">
							<div class="w-12 h-12 rounded-lg overflow-hidden">
								<img 
									v-if="classItem.coverImage && classItem.coverImage.trim() !== ''"
									:src="classItem.coverImage"
									:alt="classItem.className"
									class="w-full h-full object-cover"
								>
								<div 
									v-else 
									class="w-full h-full bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center text-white font-bold text-xl"
								>
									{{ getFirstChar(classItem.className) }}
								</div>
							</div>
							<div>
								<div class="flex items-center gap-3 mb-2">
									<h3 class="text-lg font-medium text-gray-900">{{ classItem.className }}</h3>
									<span class="text-xs text-gray-500">{{ classItem.classCode }}</span>
								</div>
								<div class="flex items-center gap-6 text-sm text-gray-600">
									<span>创建时间: {{ formatDate(classItem.createTime) }}</span>
								</div>
							</div>
						</div>
						<div class="flex items-center gap-3">
							<el-button type="primary" size="small"
								@click.stop="viewStudentList(classItem)">
								学生列表
							</el-button>
							<el-button type="danger" size="small"
								@click.stop="leaveClass(classItem)">
								解散班级
							</el-button>
						</div>
					</div>
				</div>
			</div>
		</div>

		<!-- 待处理的申请记录 -->
		<div v-if="applications.length > 0"
			class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden mt-8">
			<div class="px-6 py-4 border-b border-gray-200">
				<h3 class="text-lg font-medium text-gray-900">待处理的学生加入申请</h3>
			</div>

			<div class="overflow-x-auto">
				<table class="min-w-full divide-y divide-gray-200">
					<thead class="bg-gray-50">
						<tr>
							<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
								班级码
							</th>
							<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
								申请日期
							</th>
							<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
								学生ID
							</th>
							<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
								用户名
							</th>
							<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
								真实姓名
							</th>
							<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
								班级代码
							</th>
							<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
								状态
							</th>
							<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
								操作
							</th>
						</tr>
					</thead>
					<tbody class="bg-white divide-y divide-gray-200">
						<tr v-for="application in applications" :key="application.id">
							<td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
							{{ application.classCode }}
						</td>
							<td class="px-6 py-4 whitespace-nowrap">
								<span class="text-sm text-gray-600">{{ formatDate(application.applyDate) }}</span>
							</td>
							<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">
								{{ application.userId }}
							</td>
							<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-700">
								{{ application.username }}
							</td>
							<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-700">
								{{ application.realName || '未提供' }}
							</td>
							<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-700">
								{{ application.classCode }}
							</td>
							<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-700">
								<span :class="getApplicationStatusClass(application.status)"
									class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium">
									{{ getApplicationStatusText(application.status) }}
								</span>
							</td>
							<td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
								<div class="flex items-center gap-2">
									<el-button type="primary" size="small"
										@click="approveApplication(application)">
										通过
									</el-button>
									<el-button type="danger" size="small"
										@click="cancelApplication(application)">
										拒绝
									</el-button>
								</div>
							</td>
						</tr>
					</tbody>
				</table>
			</div>
		</div>


		<!-- 创建班级弹窗 -->
		<JoinClassDialog v-model:visible="showJoinDialog" @success="handleJoinSuccess" />

		<!-- 处理申请弹窗 -->
		<el-dialog v-model="showProcessedDialog" title="处理申请" width="90%" max-width="1200px">
			<div v-if="processedApplications.length === 0" class="text-center py-8">
				<el-empty description="暂无处理记录" />
			</div>
			<div v-else class="overflow-x-auto">
				<el-table :data="processedApplications" stripe style="width: 100%">
					<el-table-column prop="classCode" label="班级码" width="120" />
					<el-table-column prop="status" label="状态" width="100">
						<template #default="{ row }">
							<el-tag :type="getStatusTagType(row.status)" size="small">
								{{ getApplicationStatusText(row.status) }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="applyDate" label="处理时间" width="180">
						<template #default="{ row }">
							{{ formatDate(row.applyDate) }}
						</template>
					</el-table-column>
					<el-table-column prop="userId" label="学生ID" width="120" />
					<el-table-column prop="classId" label="班级ID" width="120" />
					<el-table-column prop="username" label="用户名" width="120" />
					<el-table-column prop="classCode" label="班级代码" width="120" />
					<el-table-column label="操作" width="100" fixed="right">
						<template #default>
							<span class="text-gray-500">已处理</span>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</el-dialog>


	</div>
</div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus, School, Document, Check } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { useRouter } from 'vue-router'
import JoinClassDialog from '@/components/JoinClassDialog.vue'
import { userAPI } from '@/api/user'

	// 路由
	const router = useRouter()

	// 数据
	const myClasses = ref([])
	const applications = ref([])
	const processedApplications = ref([])
	const showJoinDialog = ref(false)
	const showProcessedDialog = ref(false)
	const loading = ref(false)

	const stats = reactive({
		joinedClasses: 0,
		pendingApplications: 0,
		totalCourses: 0
	})

	// 方法
	const goHome = () => {
		window.location.href = '/home'
	}

	const loadMyClasses = async () => {
		loading.value = true
		try {
			// 调用真实API获取班级列表
			const response = await userAPI.getClassList();
			
			// 检查响应格式
			if (response && response.code === 200 && Array.isArray(response.data)) {
				// 处理返回的数据，将字段名映射到前端需要的格式
				myClasses.value = response.data.map(cls => ({
					id: cls.id,
					className: cls.name || '',
					classCode: cls.classCode || '',
					createTime: new Date().toISOString(), // API响应中没有此字段，设为当前时间
					teacherName: '', // API响应中没有此字段，设为空字符串
					teacherId: cls.teacherId || '',
					description: cls.description || '',
					startTime: '', // API响应中没有此字段，设为空字符串
					endTime: '', // API响应中没有此字段，设为空字符串
						coverImage: cls.coverImage || '' // 添加班级封面图片
				}))
				
				// 更新统计数据
				stats.joinedClasses = myClasses.value.length
			} else {
				// 处理无效响应
				ElMessage.error('获取班级列表失败，请稍后重试')
			}
		} catch (error) {
			// 处理请求错误
			console.error('获取班级列表失败:', error)
			ElMessage.error('获取班级列表失败，请稍后重试')
		} finally {
			loading.value = false
		}
	}

	const loadApplications = async () => {
	try {
		// 调用API获取申请列表
		const response = await userAPI.getPendingApplications();
		
		// 检查响应格式 - 考虑到实际API返回的是完整响应对象
		if (response && response.code === 200 && Array.isArray(response.data)) {
			// 处理返回的数据
			applications.value = response.data.map(app => ({
				id: app.id || '',
				userId: app.userId || '',
				username: app.username || '',
				realName: app.realName || '',
				classCode: app.classCode !== undefined && app.classCode !== null ? app.classCode : '未知班级码',
				applyDate: app.createTime || app.applyDate || new Date().toISOString(),
				status: app.status === 0 ? 'pending' : (app.status || 'pending'),
				classId: app.classId || ''
			}))
			
			// 更新统计数据
			stats.pendingApplications = applications.value.filter(app => app.status === 'pending').length
		} else {
			// 处理无效响应
			ElMessage.error('获取申请列表失败，请稍后重试')
		}
	} catch (error) {
		// 处理请求错误
		console.error('获取申请列表失败:', error)
		// 这里不显示错误提示，因为如果没有申请记录也会进入catch
	}
}

	const handleJoinSuccess = (classInfo) => {
		// 重新加载班级列表
		loadMyClasses()
		// 显示成功消息
		ElMessage.success('创建班级成功')
	}

	const logout = async () => {
		try {
			await ElMessageBox.confirm(
				'确认退出登录吗？',
				'退出登录',
				{
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'warning'
				}
			)
			// 清除本地存储的登录状态
			sessionStorage.removeItem('token')
			localStorage.removeItem('token')
			// 重定向到登录页面
			window.location.href = '/login'
		} catch (error) {
			// 处理用户取消操作
			if (error !== 'cancel') {
				ElMessage.error('退出登录失败，请稍后重试')
			}
		}
	}

	const viewStudentList = (classItem) => {
		router.push({
			path: '/student-members',
			query: {
				classId: classItem.id,
				className: classItem.className,
				classCode: classItem.classCode
			}
		})
	}

	const viewClassDetail = (classItem) => {
		router.push({
			path: '/class/' + classItem.id,
			query: {
				className: classItem.className,
				classCode: classItem.classCode
			}
		})
	}

	const leaveClass = async (classItem) => {
		try {
			await ElMessageBox.confirm(
				'确认解散这个班级吗？解散后班级信息将无法恢复。',
				'确认解散', {
					confirmButtonText: '确认解散',
					cancelButtonText: '取消',
					type: 'danger'
				}
			)
			// 调用API解散班级
			const response = await userAPI.dissolveClass(classItem.classCode)
			
			if (response && response.code === 200) {
				// 更新班级列表
				loadMyClasses()
				// 显示成功消息
				ElMessage.success('班级解散成功')
			} else {
				// 显示错误消息
				ElMessage.error('班级解散失败，请稍后重试')
			}
		} catch (error) {
			// 处理用户取消操作
			if (error !== 'cancel') {
				ElMessage.error('操作失败，请稍后重试')
			}
		}
	}

	const getFirstChar = (className) => {
		if (!className || typeof className !== 'string') {
			return '班'
		}
		return className.charAt(0)
	}

	const approveApplication = async (application) => {
		try {
			await ElMessageBox.confirm(
				'确认批准这个学生加入班级吗？',
				'确认批准', {
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'success'
				}
			)
			// 先更新学生申请状态，后端使用整数1表示同意状态
			const updateResponse = await userAPI.updateApplicationStatus(application.userId, 1)
			
			if (!updateResponse || updateResponse.code !== 200) {
				ElMessage.error('更新申请状态失败，请稍后重试')
				return
			}
			
			// 然后调用API同意学生加入班级
			const agreeResponse = await userAPI.agreeStudent(application.classCode, application.userId)
			
			if (!agreeResponse || agreeResponse.code !== 200) {
				ElMessage.error('同意学生加入班级失败，请稍后重试')
				return
			}
			
			// 重新加载申请列表
			loadApplications()
			// 重新加载已处理申请列表
			loadProcessedApplications()
			// 显示成功消息
			ElMessage.success('申请已批准')
		} catch (error) {
			// 处理用户取消操作
			if (error !== 'cancel') {
				ElMessage.error('操作失败，请稍后重试')
			}
		}
	}

	const cancelApplication = async (application) => {
		try {
			await ElMessageBox.confirm(
				'确认拒绝这个学生加入班级吗？',
				'确认拒绝', {
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'warning'
				}
			)
			// 调用API拒绝申请，后端使用整数2表示rejected状态
			const response = await userAPI.updateApplicationStatus(application.userId, 2)
			
			if (!response || response.code !== 200) {
				ElMessage.error('拒绝申请失败，请稍后重试')
				return
			}
			
			// 重新加载申请列表
			loadApplications()
			// 重新加载已处理申请列表
			loadProcessedApplications()
			// 显示成功消息
			ElMessage.success('申请已拒绝')
		} catch (error) {
			// 处理用户取消操作
			if (error !== 'cancel' && error !== 'close') {
				ElMessage.error('操作失败，请稍后重试')
			}
		}
	}

	const formatDate = (dateString) => {
		if (!dateString) {
			return '--'
		}
		const date = new Date(dateString)
		if (isNaN(date.getTime())) {
			return '--'
		}
		return date.toLocaleString('zh-CN', {
			year: 'numeric',
			month: '2-digit',
			day: '2-digit',
			hour: '2-digit',
			minute: '2-digit'
		})
	}

	const getApplicationStatusClass = (status) => {
		const statusMap = {
			'pending': 'bg-yellow-100 text-yellow-800',
			'approved': 'bg-green-100 text-green-800',
			'rejected': 'bg-red-100 text-red-800'
		}
		return statusMap[status] || 'bg-gray-100 text-gray-800'
	}

	const getApplicationStatusText = (status) => {
		const statusMap = {
			'pending': '待处理',
			'approved': '已通过',
			'rejected': '已拒绝'
		}
		return statusMap[status] || '未知状态'
	}

	const getStatusTagType = (status) => {
		const typeMap = {
			'pending': 'warning',
			'approved': 'success',
			'rejected': 'danger'
		}
		return typeMap[status] || 'info'
	}

	const loadProcessedApplications = async () => {
	try {
		// 调用API获取已处理的申请列表
		const response = await userAPI.getApprovedApplications();
		
		// 检查响应格式 - 后端返回完整的响应对象 {code, message, data, timestamp}
		if (response && response.code === 200 && Array.isArray(response.data)) {
			// 处理返回的数据
			processedApplications.value = response.data.map(app => ({
				id: app.id || '',
				userId: app.userId || '',
				username: app.username || '',
				realName: app.realName || '',
				classCode: app.classCode !== undefined && app.classCode !== null ? app.classCode : '未知班级码',
				applyDate: app.createTime || app.applyDate || new Date().toISOString(),
				status: app.status === 0 ? 'pending' : (app.status === 1 ? 'approved' : (app.status === 2 ? 'rejected' : 'approved')),
				classId: app.classId || ''
			}))
			
			// 更新统计数据
			stats.totalCourses = processedApplications.value.length
		} else {
			// 处理无效响应
			ElMessage.error('获取已处理申请列表失败，请稍后重试')
		}
	} catch (error) {
		// 处理请求错误
		console.error('获取已处理申请列表失败:', error)
		// 这里不显示错误提示，因为如果没有已处理的申请记录也会进入catch
	}
}

	// 生命周期
	onMounted(() => {
		// 加载班级列表
		loadMyClasses()
		// 加载待处理申请
		loadApplications()
		// 加载已处理申请
		loadProcessedApplications()
	})
</script>

<style scoped>
	.logo-icon {
		filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
	}

	.logo-icon svg {
		width: 100%;
		height: 100%;
	}
</style>